package com.jiangjiang.eshop.commodity.operation;

import com.jiangjiang.eshop.commodity.domain.PropertyGroupEntity;
import com.jiangjiang.eshop.commodity.dto.*;
import com.jiangjiang.eshop.commodity.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author Jianghaowen
 * @Date 2021/8/5
 * @Description: TODO
 * @Version V1.0
 **/
@Component
@Scope("prototype")
public class QueryCategoryPropertyOperation implements CategoryOperation<Properties>{
    /**
     * 最终结果
     */
    private final Properties properties = new Properties();

    @Autowired
    private CategoryPropertyRelationshipService categoryPropertyRelationshipService;
    @Autowired
    private PropertyService propertyService;
    @Autowired
    private PropertyGroupService propertyGroupService;
    @Autowired
    private PropertyGroupRelationshipService propertyGroupRelationshipService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public Properties doExecute(Category category) throws Exception {
        Category parentCategory = getParentCategory(category);
        if(Objects.nonNull(parentCategory)){
            parentCategory.execute(this);
        }

        List<CategoryPropertyRelationshipDTO> relations = categoryPropertyRelationshipService.listByCategoryId(category.getCategoryId());
        // 此处需要收集所有类目节点的关联数据
        properties.getPropertyRelations().addAll(relations);
        List<Long> propertyIds = relations.stream().map(CategoryPropertyRelationshipDTO::getPropertyId).collect(Collectors.toList());
        properties.getProperties().addAll(propertyService.queryByIds(propertyIds));

        List<PropertyGroupDTO> groups = propertyGroupService.listByCategoryId(category.getCategoryId());
        for (PropertyGroupDTO group : groups) {
            List<PropertyGroupRelationshipDTO> groupRelations = propertyGroupRelationshipService.queryByPropertyGroupId(group.getId());
            List<Long> Ids = groupRelations.stream().map(PropertyGroupRelationshipDTO::getPropertyId).collect(Collectors.toList());
            group.setRelationshipDTOList(groupRelations);
            group.setProperties(propertyService.queryByIds(Ids));
        }
        properties.getPropertyGroups().addAll(groups);

        return properties;
    }

    /**
     * 获取父级类目
     * @param category 当前类目节点
     * @return 父级类目节点
     */
    private Category getParentCategory(Category category) {
        CategoryDTO categoryDTO = categoryService.queryById(category.getCategoryId());
        CategoryDTO parent = categoryService.queryById(categoryDTO.getParentId());
        if(Objects.nonNull(parent)){
            return new Category(parent.getId());
        }
        return null;
    }
}
